<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
import { preOrderApi, createOrderApi, orderPayApi } from '@/apis/consult'
import { patientDetailApi } from '@/apis/patient'
import { useConsultStore } from '@/stores/consult'
import type { OrderPreData } from '@/types/consult'
import type { PatientItem } from '@/types/patient'
import { ref } from 'vue'
import CustomPayment from '@/components/custom-payment/custom-payment.vue'

const store = useConsultStore()

const customPaymentRef = ref()

// 1. 获取预支付信息
const preOrderInfo = ref<OrderPreData>()
const getPreOder = async () => {
  const res = await preOrderApi({
    type: store.type,
    illnessType: store.illnessType,
  })
  preOrderInfo.value = res
}
getPreOder()

// 2. 获取患者详情
const patientDetail = ref<PatientItem>()
const getpatientDetail = async () => {
  const res = await patientDetailApi(store.patientId)
  patientDetail.value = res
}
getpatientDetail()

// 3. 获取订单id
const orderId = ref('')
const onPaymentButtonClick = async () => {
  if (orderId.value !== '') return uni.showToast({ title: '不能重复生成订单', icon: 'none' })

  // 3.1 调用接口
  const res = await createOrderApi({
    type: store.type,
    illnessType: store.illnessType,
    patientId: store.patientId,
    depId: store.depId,
    illnessDesc: store.illnessInfo.illnessDesc,
    illnessTime: store.illnessInfo.illnessTime,
    consultFlag: store.illnessInfo.consultFlag,
    pictures: store.illnessInfo.pictures,
  })
  // 记录订单id
  orderId.value = res.id

  // 3.2 清除store中记录的问诊信息
  store.clear()

  // 3.3 弹层选择支付渠道
  customPaymentRef.value.open()
}

// 4. 处理支付渠道组件的自定义事件
const onPaymentClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  if (!res.confirm) {
    customPaymentRef.value.close()
    uni.reLaunch({ url: '/pages/index/index' })
  }
}

const onPaymentConfirm = async (index: number) => {
  if (index === undefined) return uni.showToast({ title: '请选择支付方式', icon: 'none' })
  if (index === 0) return uni.showToast({ title: '暂不支持微信支付', icon: 'none' })

  // 调用后端接口
  const { payUrl } = await orderPayApi({
    orderId: orderId.value,
    paymentMethod: index + '',
    payCallback: 'http://localhost:5173/#/subpkg_consult/room/index',
  })

  // #ifdef H5
  uni.showLoading({ title: '正在跳转支付...' })
  window.location.href = payUrl
  // #endif

  // #ifdef MP-WEIXIN
  // uni.requestPayment({

  // })
  // #endif
}
</script>

<template>
  <scroll-page v-if="preOrderInfo">
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo.payment.toFixed(2)}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo.couponDeduction.toFixed(2)}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red"> -¥{{ preOrderInfo.pointDeduction.toFixed(2) }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ preOrderInfo.actualPayment.toFixed(2) }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section
        v-if="patientDetail"
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        title="患者资料"
      >
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientDetail.name }} | {{ patientDetail.genderValue }} |
                {{ patientDetail.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ preOrderInfo.actualPayment.toFixed(2) }}</text>
      </view>
      <button class="uni-button" @click="onPaymentButtonClick">立即支付</button>
    </view>
    <!-- 支付渠道弹层 -->
    <custom-payment
      :order-id="orderId"
      :amount="preOrderInfo.actualPayment"
      ref="customPaymentRef"
      style="z-index: 999"
      @close="onPaymentClose"
      @confirm="onPaymentConfirm"
    />
  </scroll-page>
</template>

<style lang="scss">
@import './index.scss';
</style>